package us.mooresr.aircraftscheduling.server.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import us.mooresr.aircraftscheduling.server.DAO;
import us.mooresr.aircraftscheduling.shared.action.RetrieveAllOpenReservations;
import us.mooresr.aircraftscheduling.shared.action.RetrieveAllOpenReservationsAction;
import us.mooresr.aircraftscheduling.shared.action.RetrieveAllOpenReservationsResult;
import us.mooresr.aircraftscheduling.shared.model.Reservation;
import us.mooresr.aircraftscheduling.shared.model.User;

import com.googlecode.objectify.Query;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class RetrieveAllOpenReservationsHandler 
	implements ActionHandler<RetrieveAllOpenReservationsAction, RetrieveAllOpenReservationsResult> {

	@SuppressWarnings("deprecation")
	@Override
	public RetrieveAllOpenReservationsResult execute(
			RetrieveAllOpenReservationsAction arg0, ExecutionContext arg1)
			throws ActionException {
		DAO dao = new DAO();
		
		// Make a hashmap of userIDs to usernames, so we can add them to the Reservation
		HashMap<Long, String> userMap = new HashMap<Long, String>();
		Query<User> userQuery = dao.ofy().query(User.class);
		for (User u : userQuery) {
			userMap.put(u.getUserId(), u.getName());
		}
		
		ArrayList<Reservation> reservationList = new ArrayList<Reservation>();
		
		Query<Reservation> q = dao.ofy().query(Reservation.class);
		q.order("end");
		Date today = new Date();
		today.setHours(0);
		today.setMinutes(0);
		q.filter("end >=", today);
		
		for (Reservation r : q) {
			r.setReservingUserName(userMap.get(r.getReservingUserId()));
			reservationList.add(r);
		}
		
		return new RetrieveAllOpenReservationsResult(reservationList);
		
	}

	@Override
	public Class<RetrieveAllOpenReservationsAction> getActionType() {
		return RetrieveAllOpenReservationsAction.class;
	}

	@Override
	public void undo(RetrieveAllOpenReservationsAction arg0,
			RetrieveAllOpenReservationsResult arg1, ExecutionContext arg2)
			throws ActionException {
		
	}

}
